<?php
/**
 * Created by jinqiang on 2024/7/26 9:39.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Fd;


use App\Http\Models\Mysql\SsyBnInvoiceListDetailTable;
use App\Http\Models\Mysql\SsyBnInvoiceListHongchongTable;
use App\Http\Models\Mysql\SsyBnInvoiceListHuiTable;
use App\Http\Models\Mysql\SsyBnInvoiceListKpLogTable;
use App\Http\Models\Mysql\SsyBnInvoiceListShopTable;
use App\Http\Models\Mysql\SsyBnInvoiceListTable;
use App\Http\Repository\NNuoRepository;
use Illuminate\Support\Facades\DB;
use phpDocumentor\Reflection\Types\Float_;

class InvoiceService
{
    public function search($param)
    {
        $conn = (new SsyBnInvoiceListTable())->where('merge_status', (Int)$param['type']);
        if($param['sellerid'] ?? ""){
            $conn = $conn->where('sellerid', $param['sellerid']);
        }
        if($param['sourceid'] ?? ""){
            $sourceId = explode(",", str_replace("，", ",", $param['sourceid']));
            $conn = count($sourceId) > 1 ? $conn->whereIn('sourceid', $sourceId) : $conn->where('sourceid', $param['sourceid']);
        }
        if(isset($param['status']) && $param['status'] != ""){
            $conn = $conn->where('status', $param['status']);
        }
        if($param['invoicing_status'] ?? ""){
            $conn = $conn->whereIn('invoicing_status', $param['invoicing_status']);
        }
        if($param['buyername'] ?? ""){
            $conn = $conn->where('buyername', $param['buyername']);
        }
        if($param['invoice_header'] ?? ""){
            $conn = $conn->where('invoice_header', $param['invoice_header']);
        }
        if($param['invoicing_number'] ?? ""){
            $conn = $conn->where('invoicing_number', $param['invoicing_number']);
        }
        if($param['kai_createtime'] ?? []){
            $start = $param['kai_createtime'][0]." 00:00:00";
            $end = $param['kai_createtime'][1]." 23:59:59";
            $conn = $conn->whereBetween('kai_createtime', [$start, $end]);
        }
        $res = $conn->orderBy('createtime', 'desc')->paginate((Int)$param['limit'])->toArray();
        $sourceIds = array_column($res['data'], 'sourceid');
        $detailMap = [];
        if(!empty($sourceIds)){
            $field = ["id","son_order_no","product_name","num","sku_title","sku_code","pay_amount","sourceid"];
            $detailList = (new SsyBnInvoiceListDetailTable())->whereIn('sourceid', $sourceIds)->get($field)->toArray();
            foreach ($detailList as $item){
                $detailMap[$item['sourceid']][] = $item;
            }
        }
        $invoiceserialNums = array_column($res['data'], 'invoiceserialnum');
        $urlMap = [];
        if(!empty($invoiceserialNums)){
            $urlList = (new SsyBnInvoiceListHuiTable())->whereIn('c_fpqqlsh', $invoiceserialNums)->get(['c_url', 'c_fpqqlsh'])->toArray();
            $urlMap = array_column($urlList, 'c_url', 'c_fpqqlsh');
        }
        foreach($res['data'] as &$item){
            $item['order_detail'] = $detailMap[$item['sourceid']] ?? [];
            $item['c_url'] = $urlMap[$item['invoiceserialnum']] ?? "";
        }
        unset($item);
        return [
            'data' => $res['data'],
            'total' => $res['total']
        ];
    }

    //待开票列表
    public function searchKp($param)
    {
        $mergeStatus = (Int)$param['type'] === 1 ? 1 : 0;
        $conn = (new SsyBnInvoiceListTable())->where('merge_status', $mergeStatus);
        if($param['sellerid'] ?? ""){
            $conn = $conn->where('sellerid', $param['sellerid']);
        }
        if($param['sourceid'] ?? ""){
            $sourceId = explode(",", str_replace("，", ",", $param['sourceid']));
            $conn = count($sourceId) > 1 ? $conn->whereIn('sourceid', $sourceId) : $conn->where('sourceid', $param['sourceid']);
        }
        if($param['invoicing_status'] ?? ""){
            $conn = $conn->where('invoicing_status', $param['invoicing_status']);
        }
        if($param['buyername'] ?? ""){
            $conn = $conn->where('buyername', $param['buyername']);
        }
        if($param['invoice_header'] ?? ""){
            $conn = $conn->where('invoice_header', $param['invoice_header']);
        }
        if($param['invoicing_number'] ?? ""){
            $conn = $conn->where('invoicing_number', $param['invoicing_number']);
        }
        if($param['groups'] == 1){//开票
            //hongchong_status 0未开票 1已开票 2开票失败  3申请冲红 4冲红成功  5冲红失败
            //hongchong_status 2 需要 1不需要
            $conn = $conn->whereIn('invoicing_status', ["0", "2", "4"])->where('hongchong_status', 2);
        }
        if($param['groups'] == 2){//冲红
            $conn = $conn->where('status', 1)->whereIn('invoicing_status', ["3", "5"])->where('hongchong_status', 2);
        }
        //0 单张  1 多合一
        if($mergeStatus === 1){
            $mergeTagList = $conn->groupBy('merge_tag')->get(['merge_tag'])->toArray();
            $total = count($mergeTagList);
            list($page, $limit) = [(Int)$param['page'], (Int)$param['limit']];
            $data = array_splice($mergeTagList, ($page-1)*$limit, $limit);
            $invoiceList = (new SsyBnInvoiceListTable())->whereIn('merge_tag', array_column($data, 'merge_tag'))->get()->toArray();
            $field = ["id","son_order_no","product_name","num","sku_title","sku_code","pay_amount","sourceid"];
            $detailList = (new SsyBnInvoiceListDetailTable())->whereIn('sourceid', array_column($invoiceList, 'sourceid'))->get($field)->toArray();
            $detailMap = [];
            foreach ($detailList as $item){
                $detailMap[$item['sourceid']][] = $item;
            }
            $invoiceMap = [];
            foreach ($invoiceList as $item){
                $item['order_detail'] = $detailMap[$item['sourceid']];
                $invoiceMap[$item['merge_tag']][] = $item;
            }
            return ['data' => array_values($invoiceMap), 'total' => $total];
        }else {
            $res = $conn->orderBy('id', 'desc')->paginate((Int)$param['limit'])->toArray();
            $sourceIds = array_column($res['data'], 'sourceid');
            $detailMap = [];
            if(!empty($sourceIds)){
                $field = ["id","son_order_no","product_name","num","sku_title","sku_code","pay_amount","sourceid"];
                $detailList = (new SsyBnInvoiceListDetailTable())->whereIn('sourceid', $sourceIds)->get($field)->toArray();
                foreach ($detailList as $item){
                    $detailMap[$item['sourceid']][] = $item;
                }
            }
            foreach ($res['data'] as &$item){
                $item['order_detail'] = $detailMap[$item['sourceid']] ??  [];
            }
            unset($item);
            return ['data' => $res['data'], 'total' => $res['total']];
        }
    }

    public function searchMore($param)
    {
        $conn = (new SsyBnInvoiceListTable())->where('merge_status', 1);
        if($param['sellerid'] ?? ""){
            $conn = $conn->where('sellerid', $param['sellerid']);
        }
        if($param['sourceid'] ?? ""){
            $sourceId = explode(",", str_replace("，", ",", $param['sourceid']));
            $conn = count($sourceId) > 1 ? $conn->whereIn('sourceid', $sourceId) : $conn->where('sourceid', $param['sourceid']);
        }
        if($param['buyername'] ?? ""){
            $conn = $conn->where('buyername', $param['buyername']);
        }
        if($param['invoice_header'] ?? ""){
            $conn = $conn->where('invoice_header', $param['invoice_header']);
        }
        if($param['invoicing_number'] ?? ""){
            $conn = $conn->where('invoicing_number', $param['invoicing_number']);
        }
        switch ($param['type']){
            case "1":
                $conn = $conn->where('hongchong_status', 2)->whereIn('invoicing_status', ["0", "2", "4"]);
                break;
            case "2":
                $conn = $conn->where('status', 1)->where('hongchong_status', 2)->where('invoicing_status', 1);
                break;
            case "3":
                $conn = $conn->whereIn('hongchong_status', ["1", "2"])->whereIn('invoicing_status', ["0", "4"]);
                break;
            case "4":
                $conn = $conn->where('hongchong_status', 1)->where('invoicing_status', 4);
                break;
        }
        $mergeTagList = $conn->groupBy('merge_tag')->get(['merge_tag'])->toArray();
        $total = count($mergeTagList);
        list($page, $limit) = [(Int)$param['page'], (Int)$param['limit']];
        $data = array_splice($mergeTagList, ($page-1)*$limit, $limit);
        $invoiceList = (new SsyBnInvoiceListTable())->whereIn('merge_tag', array_column($data, 'merge_tag'))->get()->toArray();
        $field = ["id","son_order_no","product_name","num","sku_title","sku_code","pay_amount","sourceid"];
        $detailList = (new SsyBnInvoiceListDetailTable())->whereIn('sourceid', array_column($invoiceList, 'sourceid'))->get($field)->toArray();
        $detailMap = [];
        foreach ($detailList as $item){
            $detailMap[$item['sourceid']][] = $item;
        }
        $invoiceMap = [];
        foreach ($invoiceList as $item){
            $item['order_detail'] = $detailMap[$item['sourceid']] ?? [];
            $invoiceMap[$item['merge_tag']][] = $item;
        }
        return ['data' => array_values($invoiceMap), 'total' => $total];
    }

    public function getShop()
    {
        return (new SsyBnInvoiceListShopTable())->select(["sellerid", "sellertitle"])->groupBy(["sellerid", "sellertitle"])->get()->toArray();
    }

    public function detail($sourceId)
    {
        $invoiceObj = (new SsyBnInvoiceListTable())->where('sourceid', $sourceId)->first()->toArray();
        $field = ["id","son_order_no","product_name","num","sku_title","sku_code","pay_amount","sourceid"];
        $invoiceObj['order_detail'] = (new SsyBnInvoiceListDetailTable())->where('sourceid', $sourceId)->get($field)->toArray();
        $field = ["type","createtime","sourceidarr","order_no","invoice_header","invoice_headerid","opening_bank","opening_bank_number",
            "opening_bank_tel","opening_bank_address","email","notes","operator_user","invoicing_number","invoiceserialnum","order_detail"];
        $logList = (new SsyBnInvoiceListKpLogTable())->where('sourceidarr', 'like', '%'.$sourceId.'%')->get($field)->toArray();
        $orderNos = array_column($logList, 'order_no');
        $invoiceHuiObj = (new SsyBnInvoiceListHuiTable())->whereIn('c_orderno', $orderNos)->get(['c_orderno', 'c_url'])->toArray();
        $urls = array_column($invoiceHuiObj, 'c_url', 'c_orderno');
        foreach($logList as &$item){
            $item['order_detail'] = unserialize($item['order_detail']);
            $item['c_url'] = $urls[$item['order_no']] ?? "";
        }
        unset($item);
        return [
            'detail' => $invoiceObj,
            'detail_log' => $logList
        ];
    }

    public function chDetail($sourceIds)
    {
        $field = ["sourceid","invoice_headerid","invoice_header","email","invoicing_number","opening_bank","opening_bank_number",
            "opening_bank_tel","opening_bank_address","notes", "hongchong_status"];
        $invoiceObj = (new SsyBnInvoiceListTable())->whereIn('sourceid', $sourceIds)->first($field)->toArray();
        //查下开票信息
        $kpLogObj = (new SsyBnInvoiceListKpLogTable())->where('sourceidarr', serialize($sourceIds))->first(['order_no']);
        if(!empty($kpLogObj)){
            $invoiceHuiObj = (new SsyBnInvoiceListHuiTable())->where('c_orderno', $kpLogObj->order_no)->first();
            $invoiceObj['c_fphm'] = $invoiceHuiObj->c_fphm ?? "";
            $invoiceObj['c_fpdm'] = $invoiceHuiObj->c_fpdm ?? "";
        }
        $invoiceObj['sourceIds'] = $sourceIds;
        $field = ["id","son_order_no","product_name","num","sku_title","sku_code","pay_amount","sourceid"];
        $invoiceObj['order_detail'] = (new SsyBnInvoiceListDetailTable())->whereIn('sourceid', $sourceIds)->get($field)->toArray();

        return $invoiceObj;
    }

    public function newDetail($sourceId)
    {
        $field = ["pay_amount","notes","order_detail","opening_bank_tel","opening_bank_address","opening_bank_number","opening_bank",
            "email","sourceid","invoicing_number","invoice_header","invoice_headerid","sellerid"];
        $invoiceObj = (new SsyBnInvoiceListHongchongTable())->where('sourceid', $sourceId)->first($field);
        if(empty($invoiceObj)){
            return [];
        }
        $field = ["id","son_order_no","product_name","sku_title","sku_code","sourceid"];
        $detailList = (new SsyBnInvoiceListDetailTable())->where('sourceid', $sourceId)->get($field)->toArray();
        $detailIds = array_column($detailList, 'id');
        $amountList = (new SsyBnInvoiceListHongchongTable())->where('sourceid', $sourceId)->whereIn('tid', $detailIds)->get(['tid','pay_amount','num'])->toArray();
        $amountMap = array_column($amountList, null, 'tid');
        foreach($detailList as &$item){
            $item['pay_amount'] = $amountMap[$item['id']]['pay_amount'] ?? "";
            $item['num'] = $amountMap[$item['id']]['num'] ?? "";
        }
        unset($item);
        $invoiceObj['order_detail'] = $detailList;
        return $invoiceObj;
    }

    public function applyCH($param)
    {
        $chStatus = $param['ch_status'];
        $sourceIds = $param['sourceIds'];
        $kpLogObj = (new SsyBnInvoiceListKpLogTable())->where('sourceidarr', serialize(isset($sourceIds[1]) ? $sourceIds : $sourceIds[0]))->first();
        $orderNo = $kpLogObj->order_no ?? "";
        DB::beginTransaction();
        if($chStatus == 1){//冲红不开票
            $invoiceObj = (new SsyBnInvoiceListTable())->whereIn('sourceid', $sourceIds)->first()->toArray();
            $invoiceDetails = (new SsyBnInvoiceListDetailTable())->whereIn('sourceid', $sourceIds)->get()->toArray();
            foreach($invoiceDetails as $item){
                $data = [
                    "hongchong_status" => $chStatus,
                    "invoice_headerid" => $invoiceObj['invoice_headerid'],
                    "order_no" => $orderNo,
                    "sellerid" => $invoiceObj['sellerid'],
                    "pay_amount" => $item['pay_amount'],
                    "taskid" => $invoiceObj['taskid'],
                    "sourceid" => $item['sourceid'],
                    "email" => $invoiceObj['email'],
                    "invoice_header" => $invoiceObj['invoice_header'],
                    "invoicing_number" => $invoiceObj['invoicing_number'],
                    "opening_bank" => $invoiceObj['opening_bank'],
                    "opening_bank_number" => $invoiceObj['opening_bank_number'],
                    "opening_bank_tel" => $invoiceObj['opening_bank_tel'],
                    "opening_bank_address" => $invoiceObj['opening_bank_address'],
                    "order_detail" => $invoiceObj['order_detail'],
                    "notes" => $invoiceObj['notes'],
                    "tid" => $item['id'],
                    "num" => $item['num'],
                    "hong_number"=>"Hc".date('YmdHis',time()),
                    "createtime"=>date("Y-m-d H:i:s",time())
                ];
                $createRes = (new SsyBnInvoiceListHongchongTable())->createData($data);
                if($createRes['code'] !== 0){
                    DB::rollBack();
                    return $createRes;
                }
            }
        }else{//冲红再开票
            if(empty($param['invoice_header']) || empty($param['email'])){
                DB::rollBack();
                return ['code' => -1, 'msg' => '缺少必填参数'];
            }
            foreach ($param['order_detail'] as $item){
                $data = [
                    "hongchong_status" => $chStatus,
                    "order_no" => $orderNo,
                    "invoice_headerid" => $param['invoice_headerid'],
                    "sourceid" => $item['sourceid'],
                    "email" => $param['email'],
                    "invoice_headerid" => $param['invoice_headerid'],
                    "invoice_header"=>$param['invoice_header'],
                    "invoicing_number"=>$param['invoicing_number'] ?? "",
                    "opening_bank"=>$param['opening_bank'] ?? "",
                    "opening_bank_number"=>$param['opening_bank_number'] ?? "",
                    "opening_bank_tel"=>$param['opening_bank_tel'] ?? "",
                    "opening_bank_address"=>$param['opening_bank_address'] ?? "",
                    "order_detail"=> serialize($param['order_detail']),
                    "notes"=>$param['notes'],
                    "operator_user" => auth()->guard("api")->user()->name,
                    "tid" => (Int)$item['id'],
                    "pay_amount" => $item['pay_amount'],
                    "num" => $item['num'],
                    "hong_number"=>"Hc".date('YmdHis',time()),
                    "createtime"=>date("Y-m-d H:i:s",time())
                ];
                $createRes = (new SsyBnInvoiceListHongchongTable())->createData($data);
                if($createRes['code'] !== 0){
                    DB::rollBack();
                    return $createRes;
                }
            }
        }
        // 默认0未开票 1已开票 2开票失败  3申请冲红 4冲红成功 5冲红失败
        $res = (new SsyBnInvoiceListTable())->updateDataWhere(['sourceid' => ['in' => $sourceIds]], ['invoicing_status' => 3]);
        if($res['code'] !== 0){
            DB::rollBack();
            return $res;
        }
        DB::commit();
        return ['code' => 0, 'msg' => '发起冲红成功'];
    }

    //设置开票、冲红
    public function setKpch($groups, $sourceIds)
    {
        $invoiceList = (new SsyBnInvoiceListTable())->whereIn('sourceid', $sourceIds)->get()->toArray();
        //过滤判断
        foreach ($invoiceList as $item){
            //开个人票 抬头 邮箱不能为空
            if($item['invoice_headerid'] == "900" && (empty($item['invoice_header']) || empty($item['email']))){
                return ['code' => -1, 'msg' => '开个人票, 抬头、邮箱不能为空'];
            }
            //开企业票 抬头 邮箱 税号 不能为空
            if($item['invoice_headerid']=="18661" && (empty($item['invoice_header']) || empty($item['email']) ||
                empty($item['invoicing_number']))) {
                return ['code' => -1, 'msg' => '开企业票, 抬头、邮箱、税号不能为空'];
            }
        }
        $sellerIds = array_column($invoiceList, 'sellerid');
        $shopList = (new SsyBnInvoiceListShopTable())->whereIn('sellerid', $sellerIds)->groupBy(["sellerid", "sellertitle"])
            ->get(["sellerid", "sellertitle"])->toArray();
        $shopMap = array_column($shopList, 'sellertitle', 'sellerid');
        $field = ["id","son_order_no","product_name","num","sku_title","sku_code","pay_amount","sourceid"];
        $detailList = (new SsyBnInvoiceListDetailTable())->whereIn('sourceid', $sourceIds)->get($field)->toArray();
        $detailMap = [];
        $detailMapList = [];
        foreach($detailList as $item){
            $detailMapList[$item['sourceid']][] = $item;
            if($groups == 1){//开票
                $amount = round($item['pay_amount']/1.13,2);
                $detailMap[$item['sourceid']][] = [
                    'goodsName' => "汉服",
                    'specType' => $item['sku_code'],
                    'goodsCode' => "104020199",
                    'withTaxFlag' => 0,
                    'num' => $item['num'],
                    'unit' => '件',
                    'taxExcludedAmount' => $amount,//不含税金额
                    'price' => round($amount/$item['num'],3),//不含税 单价
                    'tax' => round($item['pay_amount']-$amount,2),//税额 [不含税金额] * [税率]
                    'taxRate' => '0.13',//税率
                    'taxIncludedAmount' => $item['pay_amount'],//含税金额 [不含税金额] + [税额]
                ];
            }
            if($groups == 2){//冲红
                $amount = round($item['pay_amount']/1.13,2);
                $detailMap[$item['sourceid']][] = [
                    'goodsName' => "汉服",
                    'specType' => $item['sku_code'],
                    'goodsCode' => "104020199",
                    'withTaxFlag' => 0,
                    'unit' => '件',
                    'num' => -($item['num']),
                    'taxExcludedAmount' => -($amount),//不含税金额
                    'price' => round($amount/$item['num'],2),
                    'tax' => -round($item['pay_amount']-$amount,2),//税额 [不含税金额] * [税率]
                    'taxRate' => '0.13',//税率
                    'taxIncludedAmount' => -$item['pay_amount']//含税金额 [不含税金额] + [税额]
                ];
            }
        }
        $error = [];
        foreach ($invoiceList as $item){
            $remark = !empty($item['notes']) ? $item['notes']."|".$shopMap[$item['sellerid']] : $shopMap[$item['sellerid']];
            $orderNo = ($groups == 1 ? "KP" : "HZ") . date('YmdHis').$item['sourceid'];
            if($groups == 1){//开票
                $order = [
                    'buyerName'=>$item['invoice_header'], //购方名称
                    'buyerTaxNum'=>$item['invoicing_number'],//购方税号
                    'buyerTel'=>$item['opening_bank_tel'],//购方电话
                    'buyerPhone'=>$item['opening_bank_tel'],//购方手机
                    'buyerAddress'=>$item['opening_bank_address'],//购方地址
                    'buyerAccount'=>$item['opening_bank']." ".$item['opening_bank_number'],//购方开户行及账号
                    'salerTaxNum'=>"91330110MA2H2FJN7J",//销方税号 339901999999142
                    'salerTel'=>'13291815370',//销方电话
                    'salerAddress'=>"浙江省杭州市西湖区三墩镇申花路792号开物创新大厦1号楼501室",//销方地址
                    'orderNo'=>$orderNo,//订单号
                    'invoiceDate'=>$item['addtime'],//订单时间
                    'clerk' => auth()->guard("api")->user()->name,//开票员
                    'pushMode'=>0,//
                    'email'=>$item['email'],//推送邮箱
                    'callBackUrl'=>"https://nnyy.13yu.com/api/cb/nnuo/invoice",//回调地址
                    'invoiceType'=>$groups,//开票类型：1:蓝票;2:红票
                    'invoiceLine'=>"pc",//发票种类：p,普通发票(电票)(默认);c,普通发票(纸票);s,专用发票;e,收购发票(电票);f,收购发票(纸质);r,普通发票(卷式);b,增值税电子专用发票;j,机动车销售统一发票;u,二手车销售统一发票;bs:电子发票(增值税专用发票)-即数电专票(电子),pc:电子发票(普通发票)-即数电普票(电子),es:数电纸质发票(增值税专用发票)-即数电专票(纸质);ec:数电纸质发票(普通发票)-即数电普票(纸质)
                    'invoiceDetail'=>$detailMap[$item['sourceid']] ?? [],
                    'remark' => $remark."|".$item['sourceid'],//备注   备注 &&  店铺+订单号 多个订单逗号隔开
                ];
            }
            if($groups == 2){//冲红
                $kpLogObj = (new SsyBnInvoiceListKpLogTable())->where('invoiceserialnum', $item['invoiceserialnum'])->where('type', 1)->orderBy('id', 'desc')
                    ->first(['order_no']);
                $kpHuiObj = (new SsyBnInvoiceListHuiTable())->where('c_orderno', $kpLogObj->order_no)
                    ->first(['c_fpdm','c_fphm','c_fpqqlsh'])->toArray();
                $order = [
                    'buyerName'=>$item['invoice_header'], //购方名称
                    'buyerTaxNum'=>$item['invoicing_number'],//购方税号
                    'buyerTel'=>$item['opening_bank_tel'],//购方电话
                    'buyerPhone'=>$item['opening_bank_tel'],//手机
                    'buyerAddress'=>$item['opening_bank_address'],//购方地址
                    'buyerAccount'=>$item['opening_bank']." ".$item['opening_bank_number'],//购方开户行及账号
                    'salerTaxNum'=>"91330110MA2H2FJN7J",//销方税号 339901999999142
                    'salerTel'=>'13291815370',//销方电话
                    'salerAddress'=>"浙江省杭州市西湖区三墩镇申花路792号开物创新大厦1号楼501室",//销方地址
                    'orderNo'=>$orderNo,//订单号
                    'invoiceDate'=>$item['addtime'],//订单时间
                    'clerk'=>auth()->guard("api")->user()->name,//开票员
                    'pushMode'=>0,//
                    'email'=>$item['email'],//推送邮箱
                    'callBackUrl'=>"https://nnyy.13yu.com/api/cb/nnuo/invoice",//回调地址
                    'invoiceType'=>$groups,//开票类型：1:蓝票;2:红票
                    'invoiceDetail'=>$detailMap[$item['sourceid']] ?? [],
                    'invoiceLine'=>"pc",
                    'invoiceCode'=>$kpHuiObj['c_fpdm'],//发票代码
                    'invoiceNum'=>$kpHuiObj['c_fphm'],//发票号码
                    'billinfoNo'=>$kpHuiObj['c_fpqqlsh'],//红字信息表编号
                    'remark'=>$remark."|".$item['sourceid'],//备注   备注 &&  店铺+订单号 多个订单逗号隔开
                ];
            }
            //生成 开票|红记录
            $addKpLog = [
                "type"=>$groups,
                "groups"=>1,
                "order_no"=>$orderNo,
                "pay_amount"=>$item['pay_amount'],
                "sourceidarr"=>serialize($item['sourceid']),
                "invoice_header"=>$item['invoice_header'],
                "invoice_headerid"=>$item['invoice_headerid'],
                "opening_bank"=>$item['opening_bank'],
                "opening_bank_number"=>$item['opening_bank_number'],
                "opening_bank_tel"=>$item['opening_bank_tel'],
                "opening_bank_address"=>$item['opening_bank_address'],
                "invoicing_number"=>$item['invoicing_number'],
                "notes"=>$item['notes'],
                "invoiceserialnum"=>'',
                "invoicing_status"=>0,
                "createtime"=>date("Y-m-d H:i:s"),
                "operator_user"=>auth()->guard("api")->user()->name,
                "email"=>$item['email'],
                "order_detail"=>serialize($detailMapList[$item['sourceid']]),
            ];
            $res = NNuoRepository::requestBillingNew(json_encode(['order' => $order], JSON_UNESCAPED_UNICODE));
            if($res['code'] == "E0000"){
                $save = [];
                if($groups == 1){
                    $save['invoicing_status'] = 1; //开票状态 默认0未开票 1已开票 2开票失败  3申请冲红 4冲红成功  5冲红失败
                    $addKpLog['invoicing_status'] = 1;
                }
                if($groups == 2){
                    $save['invoicing_status']=4; //开票状态 默认0未开票 1已开票 2开票失败  3申请冲红 4冲红成功  5冲红失败
                    $addKpLog['invoicing_status']=4;
                    $hcObj = (new SsyBnInvoiceListHongchongTable())->where('sourceid', $item['sourceid'])->orderBy("id", "desc")->first()->toArray();
                    $save['hongchong_status']=$hcObj['hongchong_status'];
                    $save['pay_amount']= (new SsyBnInvoiceListHongchongTable())->where('hong_number', $hcObj['hong_number'])->sum("pay_amount");;
                    $save['invoice_header']=$hcObj['invoice_header'];
                    $save['invoice_headerid']=$hcObj['invoice_headerid'];
                    $save['opening_bank']=$hcObj['opening_bank'];
                    $save['opening_bank_number']=$hcObj['opening_bank_number'];
                    $save['opening_bank_tel']=$hcObj['opening_bank_tel'];
                    $save['opening_bank_address']=$hcObj['opening_bank_address'];
                    $save['invoicing_number']=$hcObj['invoicing_number'];
                    $save['notes']=$hcObj['notes'];
                    $save['email']=$hcObj['email'];
                    //修改详情
                    $hcList = (new SsyBnInvoiceListHongchongTable())->where('sourceid', $item['sourceid'])->where('hong_number', $hcObj['hong_number'])
                        ->get(['tid', 'sourceid', 'pay_amount', 'num'])->toArray();
                    foreach ($hcList as $hcItem){
                        (new SsyBnInvoiceListDetailTable())->updateData($hcItem['tid'], [
                            'pay_amount' => $hcItem['pay_amount'],
                            'num' => $hcItem['num']
                        ]);
                    }
                }
                $addKpLog['invoiceserialnum'] = $res['result']["invoiceSerialNum"];
                $save['invoiceserialnum'] = $res['result']["invoiceSerialNum"];
                $save['status'] = 1;
                $save['kai_createtime'] = date("Y-m-d H:i:s");
                $save['err_msg'] = '';
                (new SsyBnInvoiceListTable())->updateDataWhere(['sourceid' => $item['sourceid']], $save);
                (new SsyBnInvoiceListKpLogTable())->createData($addKpLog);
            }else{//开票失败
                $save = [
                    'invoicing_status' => $groups == 1 ? 2: 5,
                    'err_msg' => $res['describe']
                ];
                $addKpLog = array_merge($addKpLog, $save);
                (new SsyBnInvoiceListTable())->updateDataWhere(['sourceid' => $item['sourceid']], $save);
                (new SsyBnInvoiceListKpLogTable())->createData($addKpLog);
                $error[] = ['sourceid' => $item['sourceid'], 'msg' => $res['describe']];
            }
        }
        if(!empty($error)){
            $msg = ($groups == 1 ? "开票失败：":"冲红失败：").implode(", ", array_column($error, 'sourceid'));
            return ['code' => -1, 'msg' => $msg, 'data' => $error];
        }
        return ['code' => 0];
    }

    public function setKpchMore($groups, $mergeTags)
    {
        array_unique($mergeTags);
        $error = [];
        foreach ($mergeTags as $mergeTag){
            $orderNo = ($groups == 1 ? "KP" : "HZ").date('YmdHis').$mergeTag;
            $invoiceList = (new SsyBnInvoiceListTable())->where('merge_tag', $mergeTag)->get()->toArray();
            //过滤判断
            foreach ($invoiceList as $item){
                //开个人票 抬头 邮箱不能为空
                if($item['invoice_headerid'] == "900" && (empty($item['invoice_header']) || empty($item['email']))){
                    return ['code' => -1, 'msg' => '开个人票, 抬头、邮箱不能为空'];
                }
                //开企业票 抬头 邮箱 税号 不能为空
                if($item['invoice_headerid']=="18661" && (empty($item['invoice_header']) || empty($item['email']) ||
                        empty($item['invoicing_number']))) {
                    return ['code' => -1, 'msg' => '开企业票, 抬头、邮箱、税号不能为空'];
                }
            }
            $sourceIds = array_column($invoiceList, "sourceid");
            $field = ["id","son_order_no","product_name","num","sku_title","sku_code","pay_amount","sourceid"];
            $detailList = (new SsyBnInvoiceListDetailTable())->whereIn('sourceid', $sourceIds)->get($field)->toArray();
            $detail = [];
            foreach($detailList as $item){
                if($groups == 1){//开票
                    $amount = round($item['pay_amount']/1.13,2);
                    $detail[] = [
                        'goodsName' => "汉服",
                        'specType' => $item['sku_code'],
                        'goodsCode' => "104020199",
                        'withTaxFlag' => 0,
                        'num' => $item['num'],
                        'unit' => '件',
                        'taxExcludedAmount' => $amount,//不含税金额
                        'price' => round($amount/(Int)$item['num'],3),
                        'tax' => round($item['pay_amount']-$amount,3),//税额 [不含税金额] * [税率]
                        'taxRate' => '0.13',//税率
                        'taxIncludedAmount' => $item['pay_amount'],//含税金额 [不含税金额] + [税额]
                    ];
                }
                if($groups == 2){//冲红
                    $amount = round($item['pay_amount']/1.13,2);
                    $detail[] = [
                        'goodsName' => "汉服",
                        'specType' => $item['sku_code'],
                        'goodsCode' => "104020199",
                        'withTaxFlag' => 0,
                        'unit' => '件',
                        'num' => -($item['num']),
                        'taxExcludedAmount' => -($amount),//不含税金额
                        'price' => round($amount/$item['num'],3),
                        'tax' => -round($item['pay_amount']-$amount,3),//税额 [不含税金额] * [税率]
                        'taxRate' => '0.13',//税率
                        'taxIncludedAmount' => -$item['pay_amount']//含税金额 [不含税金额] + [税额]
                    ];
                }
            }
            //备注信息
            $shopObj = (new SsyBnInvoiceListShopTable())->where('sellerid', $invoiceList[0]['sellerid'])->first();
            $remark = !empty($invoiceList[0]['notes']) ? $invoiceList[0]['notes']."|".$shopObj->sellertitle : $shopObj->sellertitle;
            if($groups == 1){//开票
                $order = [
                    'buyerName'=>$invoiceList[0]['invoice_header'], //购方名称
                    'buyerTaxNum'=>$invoiceList[0]['invoicing_number'],//购方税号
                    'buyerTel'=>$invoiceList[0]['opening_bank_tel'],//购方电话
                    'buyerPhone'=>$invoiceList[0]['opening_bank_tel'],//购方手机
                    'buyerAddress'=>$invoiceList[0]['opening_bank_address'],//购方地址
                    'buyerAccount'=>$invoiceList[0]['opening_bank']." ".$invoiceList[0]['opening_bank_number'],//购方开户行及账号
                    'salerTaxNum'=>"91330110MA2H2FJN7J",//销方税号
                    'salerTel'=>'13291815370',//销方电话
                    'salerAddress'=>"浙江省杭州市西湖区三墩镇申花路792号开物创新大厦1号楼501室",//销方地址
                    'orderNo'=>$orderNo,//订单号
                    'invoiceDate'=>$invoiceList[0]['addtime'],//订单时间
                    'clerk' => auth()->guard("api")->user()->name,//开票员
                    'pushMode'=>0,//
                    'email'=>$invoiceList[0]['email'],//推送邮箱
                    'callBackUrl'=>"https://nnyy.13yu.com/api/cb/nnuo/invoice",//回调地址
                    'invoiceType'=>$groups,//开票类型：1:蓝票;2:红票
                    'invoiceLine'=>"pc",//发票种类：p,普通发票(电票)(默认);c,普通发票(纸票);s,专用发票;e,收购发票(电票);f,收购发票(纸质);r,普通发票(卷式);b,增值税电子专用发票;j,机动车销售统一发票;u,二手车销售统一发票;bs:电子发票(增值税专用发票)-即数电专票(电子),pc:电子发票(普通发票)-即数电普票(电子),es:数电纸质发票(增值税专用发票)-即数电专票(纸质);ec:数电纸质发票(普通发票)-即数电普票(纸质)
                    'invoiceDetail' => $detail,
                    'remark' => mb_substr($remark."|".implode(",", $sourceIds), 0, 200),//备注 店铺+订单号 多个订单逗号隔开
                ];
            }
            if($groups == 2){//冲红
                $kpHuiObj = (new SsyBnInvoiceListHuiTable())->where('c_fpqqlsh', $invoiceList[0]['invoiceserialnum'])
                    ->first(['c_fpdm','c_fphm','c_fpqqlsh'])->toArray();
                $order = [
                    'buyerName'=>$invoiceList[0]['invoice_header'], //购方名称
                    'buyerTaxNum'=>$invoiceList[0]['invoicing_number'],//购方税号
                    'buyerTel'=>$invoiceList[0]['opening_bank_tel'],//购方电话
                    'buyerPhone'=>$invoiceList[0]['opening_bank_tel'],//手机
                    'buyerAddress'=>$invoiceList[0]['opening_bank_address'],//购方地址
                    'buyerAccount'=>$invoiceList[0]['opening_bank']." ".$invoiceList[0]['opening_bank_number'],//购方开户行及账号
                    'salerTaxNum'=>"91330110MA2H2FJN7J",//销方税号
                    'salerTel'=>'13291815370',//销方电话
                    'salerAddress'=>"浙江省杭州市西湖区三墩镇申花路792号开物创新大厦1号楼501室",//销方地址
                    'orderNo'=>$orderNo,//订单号
                    'invoiceDate'=>$invoiceList[0]['addtime'],//订单时间
                    'clerk'=>auth()->guard("api")->user()->name,//开票员
                    'pushMode'=>0,//
                    'email'=>$invoiceList[0]['email'],//推送邮箱
                    'callBackUrl'=>"https://nnyy.13yu.com/api/cb/nnuo/invoice",//回调地址
                    'invoiceType'=>$groups,//开票类型：1:蓝票;2:红票
                    'invoiceDetail'=>$detail,
                    'invoiceLine'=>"pc",
                    'invoiceCode'=>$kpHuiObj['c_fpdm'],//发票代码
                    'invoiceNum'=>$kpHuiObj['c_fphm'],//发票号码
                    'billinfoNo'=>$kpHuiObj['c_fpqqlsh'],//红字信息表编号
                    'remark' => mb_substr($remark."|".implode(",", $sourceIds), 0, 200),//备注   备注 &&  店铺+订单号 多个订单逗号隔开
                ];
            }
            //生成 开票|红记录
            $addKpLog = [
                "type"=>$groups,
                "groups"=>2,
                "order_no"=>$orderNo,
                "pay_amount"=>$invoiceList[0]['pay_amount'],
                "sourceidarr"=>serialize($sourceIds),
                "invoice_header"=>$invoiceList[0]['invoice_header'],
                "invoice_headerid"=>$invoiceList[0]['invoice_headerid'],
                "opening_bank"=>$invoiceList[0]['opening_bank'],
                "opening_bank_number"=>$invoiceList[0]['opening_bank_number'],
                "opening_bank_tel"=>$invoiceList[0]['opening_bank_tel'],
                "opening_bank_address"=>$invoiceList[0]['opening_bank_address'],
                "invoicing_number"=>$invoiceList[0]['invoicing_number'],
                "notes"=>$invoiceList[0]['notes'],
                "invoiceserialnum"=>'',
                "invoicing_status"=>0,
                "createtime"=>date("Y-m-d H:i:s"),
                "operator_user"=>auth()->guard("api")->user()->name,
                "email"=>$invoiceList[0]['email'],
                "order_detail"=>serialize($detailList),
            ];
            $res = NNuoRepository::requestBillingNew(json_encode(['order' => $order], JSON_UNESCAPED_UNICODE));
            if($res['code'] == "E0000"){
                if($groups == 1){
                    $save = [
                        'invoicing_status' => 1,//开票状态 默认0未开票 1已开票 2开票失败  3申请冲红 4冲红成功  5冲红失败
                        'status' => 1,
                        'invoiceserialnum' => $res['result']["invoiceSerialNum"]
                    ];
                    (new SsyBnInvoiceListTable())->updateDataWhere(['merge_tag' => $mergeTag], $save);
                    $addKpLog['invoicing_status'] = 1;
                }
                if($groups == 2){
                    $addKpLog['invoicing_status']=4;
                    foreach ($invoiceList as $item){
                        $hcObj = (new SsyBnInvoiceListHongchongTable())->where('sourceid', $item['sourceid'])->orderBy("id", "desc")->first()->toArray();
                        $save = [
                            'invoicing_status' => 4,
                            'status' => 1,
                            'invoiceserialnum' => $res['result']["invoiceSerialNum"],
                            'hongchong_status' => $hcObj['hongchong_status'],
                            'pay_amount' => (new SsyBnInvoiceListHongchongTable())->where('hong_number', $hcObj['hong_number'])->sum("pay_amount"),
                            'invoice_header' => $hcObj['invoice_header'],
                            'invoice_headerid' => $hcObj['invoice_headerid'],
                            'opening_bank' => $hcObj['opening_bank'],
                            'opening_bank_number' => $hcObj['opening_bank_number'],
                            'opening_bank_tel' => $hcObj['opening_bank_tel'],
                            'opening_bank_address' => $hcObj['opening_bank_address'],
                            'invoicing_number' => $hcObj['invoicing_number'],
                            'notes' => $hcObj['notes'],
                            'email' => $hcObj['email']
                        ];
                        (new SsyBnInvoiceListTable())->updateDataWhere(['sourceid' => $item['sourceid']], $save);
                        //修改详情
                        $hcList = (new SsyBnInvoiceListHongchongTable())->where('sourceid', $item['sourceid'])->where('hong_number', $hcObj['hong_number'])
                            ->get(['tid', 'sourceid', 'pay_amount', 'num'])->toArray();
                        foreach ($hcList as $hcItem){
                            (new SsyBnInvoiceListDetailTable())->updateData($hcItem['tid'], [
                                'pay_amount' => $hcItem['pay_amount'],
                                'num' => $hcItem['num']
                            ]);
                        }
                    }
                }
                $addKpLog['invoiceserialnum'] = $res['result']["invoiceSerialNum"];
                (new SsyBnInvoiceListKpLogTable())->createData($addKpLog);
            }else{//开票失败
                $save = [
                    'invoicing_status' => $groups == 1 ? 2: 5,
                    'err_msg' => $res['describe']
                ];
                $addKpLog = array_merge($addKpLog, $save);
                (new SsyBnInvoiceListTable())->updateDataWhere(['merge_tag' => $mergeTag], $save);
                (new SsyBnInvoiceListKpLogTable())->createData($addKpLog);
                $error[] = ['merge_tag' => $mergeTag, 'sourceid' => $sourceIds, 'msg' => $res['describe']];
            }
        }
        if(!empty($error)){
            $msg = ($groups == 1 ? "开票失败：":"冲红失败：").implode(", ", array_column($error, 'merge_tag'));
            return ['code' => -1, 'msg' => $msg, 'data' => $error];
        }
        return ['code' => 0];
    }

    public function setData($param)
    {
        if($param['invoice_headerid'] == '900' && (empty($param['invoice_header']) || empty($param['email']))){
            return ['code' => -1, 'msg' => '缺少必填信息'];
        }
        if($param['invoice_headerid'] == '18661' && (empty($param['invoice_header']) || empty($param['email']) || empty($param['invoicing_number']))){
            return ['code' => -1, 'msg' => '缺少必填信息'];
        }
        DB::beginTransaction();
        foreach ($param['sourceIds'] as $sourceId){
            $save = [
                'invoice_headerid' => $param['invoice_headerid'],
                'invoice_header' => $param['invoice_header'],
                'email' => $param['email'],
                'notes' => $param['notes'],
                'invoicing_number' => $param['invoicing_number'] ?? "",
                'opening_bank' => $param['opening_bank'] ?? "",
                'opening_bank_number' => $param['opening_bank_number'] ?? "",
                'opening_bank_tel' => $param['opening_bank_tel'] ?? "",
                'opening_bank_address' => $param['opening_bank_address'] ?? "",
                'pay_amount' => $param['pay_amount']
            ];
            if($param['type'] == "1"){ // 0 默认修改 1再次开票修改
                $save['hongchong_status']=2; //需要开票
                $save['invoicing_status']=0; //未开票
            }
            $res = (new SsyBnInvoiceListTable())->updateDataWhere(['sourceid' => $sourceId], $save);
            if($res['code'] !== 0){
                DB::rollBack();
                return ['code' => -1, 'msg' => $res['msg'], 'data' => $res];
            }
        }
        foreach ($param['order_detail'] as $item){
            $save = [
                'pay_amount' => $item['pay_amount'],
                'num' => $item['num']
            ];
            $res = (new SsyBnInvoiceListDetailTable())->updateData($item['id'], $save);
            if($res['code'] !== 0){
                DB::rollBack();
                return ['code' => -1, 'msg' => $res['msg'], 'data' => $res];
            }
        }
        DB::commit();
        return ['code' => 0];
    }

    //申请多单合一开票信息、修改多单合一开票信息
    public function setMoreData($param)
    {
        if($param['invoice_headerid'] == '900' && (empty($param['invoice_header']) || empty($param['email']))){
            return ['code' => -1, 'msg' => '缺少必填信息'];
        }
        if($param['invoice_headerid'] == '18661' && (empty($param['invoice_header']) || empty($param['email']) || empty($param['invoicing_number']))){
            return ['code' => -1, 'msg' => '缺少必填信息'];
        }
        $save = [
            'invoice_headerid' => $param['invoice_headerid'],
            'invoice_header' => $param['invoice_header'],
            'email' => $param['email'],
            'notes' => $param['notes'],
            'invoicing_number' => $param['invoicing_number'] ?? "",
            'opening_bank' => $param['opening_bank'] ?? "",
            'opening_bank_number' => $param['opening_bank_number'] ?? "",
            'opening_bank_tel' => $param['opening_bank_tel'] ?? "",
            'opening_bank_address' => $param['opening_bank_address'] ?? "",
        ];
        //申请多合一开票, 不同店铺和不同昵称不能合并
        if($param['type'] == 1){
            $sellerIdList = (new SsyBnInvoiceListTable())->whereIn('sourceid', $param['sourceIds'])->groupBy('sellerid')->get(['sellerid'])->toArray();
            if(count($sellerIdList) > 1){
                return ['code' => -1, 'msg' => '不同店铺不可合并开票'];
            }
            $buyernameList = (new SsyBnInvoiceListTable())->whereIn('sourceid', $param['sourceIds'])->groupBy('buyername')->get(['buyername'])->toArray();
            if(count($buyernameList) > 1){
                return ['code' => -1, 'msg' => '不同买家不可合并开票'];
            }
            $save['merge_status'] = 1;
            $save['merge_tag'] = $param['invoice_headerid'].date("YmdHis");
        }
        $amountTotal = [];
        foreach ($param['order_detail'] as $item){
            $amountTotal[$item['sourceid']] = ($amountTotal[$item['sourceid']] ?? 0) + (Double)$item['pay_amount'];
            (new SsyBnInvoiceListDetailTable())->updateData((Int)$item['id'], ['pay_amount' => $item['pay_amount'], 'num' => $item['num']]);
        }
        foreach($amountTotal as $sourceid => $amount){
            (new SsyBnInvoiceListTable())->updateDataWhere(['sourceid' => $sourceid], ['pay_amount' => $amount]);
        }
        return (new SsyBnInvoiceListTable())->updateDataWhere(['sourceid' => ['in' => $param['sourceIds']]], $save);
    }

    //取消多合一开票
    public function cancelMore($mergeTags)
    {
        return (new SsyBnInvoiceListTable())->updateDataWhere(['merge_tag' => ['in' => $mergeTags]], [
            'merge_tag' => '',
            'merge_status' => '0'
        ]);
    }
}
